var mysql = require('mysql')
var config = require('../config/config')
var pool = mysql.createPool(config.mysql)

/* help
  let res = await query('select * from user')
*/
//获取数据库连接
const getConnect = (callback = () => { }) => {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, conn) => {
      if (err) reject(err)
      try {
        let res = callback(conn)
        resolve(res)
      } catch (e) {
        reject(e)
      } finally {
        try{
          conn.release()
        }catch(e){
          console.error('数据库异常：'.e);
        }
      }
    })
  })
}

//统一查询方法
const query = function (sql, parms = []) {
  // console.log(sql,parms);
  return new Promise((resolve, reject) => {
    getConnect((conn) => {
      conn.query(sql, parms, (err, result, fields) => {
        if (err) reject(err)
        resolve({
          result,
          fields
        })
      })
    })
  })
}

//获取所有记录
const getAll = function (sql = "", parms = []) {
  return query(sql, parms).then((res) => {
    return res.result;
  });
}
//获取单个结果
const getRow = function (sql = "", parms = []) {
  return query(sql, parms).then((res) => {
    return res.result.shift();
  });
}
//获取数量
const getCount = function (sql = "", parms = []) {
  return getRow(sql, parms).then((res) => {
    let keys = Object.keys(res);
    if (keys.length > 0) {
      let oneKey = keys.shift();
      let oneData = res[oneKey];
      return Number(oneData);
    }
    return 0;
  });
};
//获取影响的行数
const exec = function (sql = "", parms = [], fields = false) {
  return query(sql, parms).then((res) => {
    return fields ? res : res.result.affectedRows;
  });
};

module.exports = {
  getConnect,
  query,
  getAll,
  getRow,
  getCount,
  exec,
}